import React from 'react';
import {Table, Icon} from 'antd';
import TableBase from './table';
import g from '../../global';

export default class Record extends TableBase {
    done(data, meta) {
        const pageNo = meta.page.index || 1;
        const pageSize = meta.page.size;
        const pages = {
            current: pageNo,
            pageSize,
            total: data.total,
            showSizeChanger: true,
            showQuickJumper: true,
            pageSizeOptions: ['10', '20', '30'],
            onShowSizeChange: this.onSize.bind(this),
            onChange: this.onPage.bind(this)
        };
        let colWidth, colRange, maxCols = 6;
        const colCount = data.fields.length;
        if (colCount > maxCols) {
            colRange = [0, colCount - 1];
            colWidth = (100 / maxCols) + '%';
        } else {
            colWidth = (100 / colCount) + '%';
            maxCols = undefined;
        }
        const columns = data.fields.map((field, index) => ({
            key: index,
            width: colWidth,
            title: field.name,
            dataIndex: field.name,
            render: text => {
                if (typeof text === 'object') {
                    // 居然有这样的数据！？
                    return <Icon type="ellipsis"/>;
                }
                return <span>{text}</span>;
            }
        }));
        return (
            <Table
                bordered rowClassName={g.tableRowClass}
                columns={columns} dataSource={data.rows}
                columnsPageRange={colRange} columnsPageSize={maxCols}
                rowKey={(row, idx) => idx} useFixedHeader pagination={pages}
            />
        );
    }

    onPage(page) {
        const {conn, db, table} = this.context.params;
        this.context.actions.dbms.record.get(conn, db, table, page);
    }

    onSize(page, size) {
        if (this.context.state.dbms.global.pageSize !== size) {
            this.context.actions.dbms.global.setPageSize(size);
            this.onPage(this.get().meta.page.index || 1);
        }
    }
}
